package com.jinzo.mporaba;

import android.app.Dialog;
import android.app.ListActivity;
import android.appwidget.AppWidgetManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.util.Linkify;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.ArrayAdapter;
import android.content.Intent;


import java.util.ArrayList;

import com.jinzo.mporaba.tasks.LoadFromCPTask;
import com.jinzo.mporaba.tasks.LoadFromSOAPTask;
import com.jinzo.mporaba.tasks.SaveToCPTask;

public class Mporaba extends ListActivity {
   
    private ArrayList<QuotaItem> m_items = null;
    private ItemAdapter m_adapter;
    private SharedPreferences pref;
    private ConnectivityManager connManager;
    private Button refresh_button;

    static final int SHOW_WIFI_PREFERENCES = 10;
    static final int SHOW_MOBILE_PREFERENCES = 9;
    static final int SHOW_WIRELESS_PREFERENCES = 8;
    static final int DIALOG_NO_MOBILE = 7;
    static final int DIALOG_NO_WIFI = 6;
    static final int DIALOG_FIRST_RUN = 5;
    static final int DIALOG_UNKNOWN_ERROR = 4;
    static final int DIALOG_NO_CONNECTION = 3;
    static final int DIALOG_WORKING = 2;
    static final int SHOW_PREFERENCES = 1;
    static final int DIALOG_WRONG_PASSWORD = 0;
    
    public static final int REQUEST_SUCCESS = 100;
    public static final int REQUEST_ERROR_SOAP = 101;
    public static final int REQUEST_ERROR_CONNECTION = 102;
    public static final int REQUEST_ERROR_LOGIN = 103;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.main);
        refresh_button = (Button)findViewById(R.id.refresh_button);
        pref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        /* Connectivity */
        connManager= (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connManager.getActiveNetworkInfo();
        /* List adapter n'stuff */
        m_items = new ArrayList<QuotaItem>();
        m_adapter = new ItemAdapter(this, R.layout.row, m_items);
        setListAdapter(m_adapter);
        
        /* To show the button or not, is the question. */
        if (!pref.getBoolean("gumb_osvezi", true)) {
        	refresh_button.setVisibility(8);
        } else {
        	refresh_button.setVisibility(0);
        }
        /* Basic control code, what to do on startup */
        if (pref.getBoolean("osvezi_ob_zagonu", false) || pref.getString("nacin_povezave", "") == "") {
        	if (info == null || !info.isConnected()) {
        		showDialog(DIALOG_NO_CONNECTION);
        	} else {
                if (info.getTypeName() == "MOBILE" && pref.getString("nacin_povezave", "") == "samo_wifi") {
                	showDialog(DIALOG_NO_WIFI);
                } else if (info.getTypeName() == "WIFI" && pref.getString("nacin_povezave", "") == "samo_mobi") {
                	showDialog(DIALOG_NO_MOBILE);
                } 
        	}
            if (pref.getString("username","") == "" || pref.getString("password","") == "") {
             	showDialog(DIALOG_WRONG_PASSWORD);
            } else {
                refreshFromNET();
            }
            if (pref.getString("nacin_povezave", "") == "") {
            	// First run
            	SharedPreferences.Editor editor = pref.edit();
            	editor.putString("nacin_povezave", "wifi_drugace_mobi");
                editor.commit();
            } 
        } else {
        	refreshFromCP();
        }
    	refresh_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	refresh_button.setClickable(false);
                refreshFromNET();
            }
        });
    }
    private void refreshFromCP() {
    	refresh_button.setClickable(false);
    	setProgressBarIndeterminateVisibility(true);

    	final LoadFromCPTask loadcp = new LoadFromCPTask();
    	
    	Handler cphandler = new Handler() {
    	    public void handleMessage(Message msg) {
    	    	switch(msg.what) {
    				case Mporaba.REQUEST_SUCCESS:
    					m_items.clear();
    					m_items.addAll(loadcp.getResult());
    					m_adapter.notifyDataSetChanged();
    					setProgressBarIndeterminateVisibility(false);
    					refresh_button.setClickable(true);
    					break;
    	    	}
    		}
    	};
    	
    	loadcp.load(getBaseContext(), cphandler);  
  	  	   	
    }
    public void refreshFromNET() {
    	refresh_button.setClickable(false);
    	setProgressBarIndeterminateVisibility(true);
        /* Here be dragons, no really, switch this when implementing the other API and we're done.*/
    	final LoadFromSOAPTask load = new LoadFromSOAPTask();
    	
    	Handler handler = new Handler() {
    	    public void handleMessage(Message msg) {
    	    	switch(msg.what) {
    				case Mporaba.REQUEST_SUCCESS:
    					m_items.clear();
    					m_items.addAll(load.getResult());
    					m_adapter.notifyDataSetChanged();
    			    	Handler save_handler = new Handler() {
    			    	    public void handleMessage(Message msg) {
    			    	    	switch(msg.what) {
    			    				case Mporaba.REQUEST_SUCCESS:
    			    					refreshWidgets();
    			    					setProgressBarIndeterminateVisibility(false);
    			    					refresh_button.setClickable(true);
    			    	    	}
    			    	    }
    			    	};
    					final SaveToCPTask save = new SaveToCPTask();
    					save.load(getBaseContext(), m_items, save_handler);
    					break;			
    				case Mporaba.REQUEST_ERROR_SOAP:
    					setProgressBarIndeterminateVisibility(false);
    					refresh_button.setClickable(true);
    					break;
    				case Mporaba.REQUEST_ERROR_CONNECTION:
    					setProgressBarIndeterminateVisibility(false);
    					refresh_button.setClickable(true);
    					showDialog(DIALOG_NO_CONNECTION);
    					break;
    				case Mporaba.REQUEST_ERROR_LOGIN:
    					setProgressBarIndeterminateVisibility(false);
    					refresh_button.setClickable(true);
    					showDialog(DIALOG_WRONG_PASSWORD);
    					break;
    	    	}
    		}
    	};
    	
    	load.load(pref.getString("username", ""), pref.getString("password", ""), handler);

    }
	
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
        switch(id) {
        case DIALOG_WRONG_PASSWORD:
        	dialog = new Dialog(Mporaba.this);
        	dialog.setContentView(R.layout.dialog_wrong_password);
        	dialog.setTitle("Podatki ob prvem zagonu");
        	TextView t = (TextView) dialog.findViewById(R.id.wrong_password_text);
        	Linkify.addLinks(t, Linkify.WEB_URLS);
        	Button save = (Button) dialog.findViewById(R.id.save_dialog);
        	Button quit = (Button) dialog.findViewById(R.id.quit_dialog);
        	EditText u = (EditText) dialog.findViewById(R.id.entry_username);
        	EditText p = (EditText) dialog.findViewById(R.id.entry_password);
        	u.setText(pref.getString("username",""));
        	p.setText(pref.getString("password",""));
        	save.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    SharedPreferences.Editor editor = pref.edit();
                    editor.putString("username", ((EditText) v.getRootView().findViewById(R.id.entry_username)).getText().toString());
                    editor.putString("password", ((EditText) v.getRootView().findViewById(R.id.entry_password)).getText().toString());
                    editor.commit();
                    dismissDialog(DIALOG_WRONG_PASSWORD);
                    refreshFromNET();
                }
            });
        	quit.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                     Mporaba.this.finish();
                 }
            });        	
            break;
        case DIALOG_NO_CONNECTION:
        	dialog = new Dialog(Mporaba.this);
        	dialog.setContentView(R.layout.dialog_no_connection);
        	dialog.setTitle("Napaka v povezavi z internetom");
        	Button dialog_no_connection_ok = (Button) dialog.findViewById(R.id.dialog_no_connection_ok);
        	Button dialog_no_connection_quit = (Button) dialog.findViewById(R.id.dialog_no_connection_quit);
        	dialog_no_connection_ok.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent wirelessSettingsActivity = new Intent("android.settings.WIRELESS_SETTINGS");
                    startActivityForResult(wirelessSettingsActivity, SHOW_WIRELESS_PREFERENCES);
                }
            });
        	dialog_no_connection_quit.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	dismissDialog(DIALOG_NO_CONNECTION);
                	finish();
                }
            }); 
        	break;
        case DIALOG_UNKNOWN_ERROR:
        	dialog = new Dialog(Mporaba.this);
        	dialog.setContentView(R.layout.dialog_unknown_error);
        	dialog.setTitle("Prišlo je do neznane napake.");
        	Button ok = (Button) dialog.findViewById(R.id.unknown_error_ok);
        	ok.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dismissDialog(DIALOG_UNKNOWN_ERROR);
					
				}
			});
        	break;
        case DIALOG_NO_WIFI:
        	dialog = new Dialog(Mporaba.this);
        	dialog.setContentView(R.layout.dialog_no_connection);
        	dialog.setTitle("Napaka v povezavi z internetom");
        	Button dialog_no_wifi_ok = (Button) dialog.findViewById(R.id.dialog_no_wifi_ok);
        	Button dialog_no_wifi_quit = (Button) dialog.findViewById(R.id.dialog_no_wifi_quit);
        	dialog_no_wifi_ok.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent wirelessSettingsActivity = new Intent("android.settings.WIRELESS_SETTINGS");
                    startActivityForResult(wirelessSettingsActivity, SHOW_WIFI_PREFERENCES);
                }
            });
        	dialog_no_wifi_quit.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	dismissDialog(DIALOG_NO_WIFI);
                	finish();
                }
            });         	
        	break;
        case DIALOG_NO_MOBILE:
        	dialog = new Dialog(Mporaba.this);
        	dialog.setContentView(R.layout.dialog_no_connection);
        	dialog.setTitle("Napaka v povezavi z internetom");
        	Button dialog_no_mobile_ok = (Button) dialog.findViewById(R.id.dialog_no_mobile_ok);
        	Button dialog_no_mobile_quit = (Button) dialog.findViewById(R.id.dialog_no_mobile_quit);
        	dialog_no_mobile_ok.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Intent wirelessSettingsActivity = new Intent("android.settings.WIRELESS_SETTINGS");
                    startActivityForResult(wirelessSettingsActivity, SHOW_MOBILE_PREFERENCES);
                }
            });
        	dialog_no_mobile_quit.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	dismissDialog(DIALOG_NO_MOBILE);
                	finish();
                }
            });         	
        	break;
        default:
            dialog = null;
        }
        return dialog;
    }	
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem it) {
	    // Handle item selection
	    switch (it.getItemId()) {
	    case R.id.refresh:   
	    	refreshFromNET();
	        return true;
	    case R.id.preferences:
            Intent settingsActivity = new Intent(getBaseContext(), Preferences.class);
            startActivityForResult(settingsActivity, SHOW_PREFERENCES);
	    	return true;
	    case R.id.quit:
	        finish();
	        return true;
	    default:
	        return super.onOptionsItemSelected(it);
	    }
	}	
	public void refreshWidgets() {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getBaseContext());
        MonitorWidget mw = new MonitorWidget();
        RemoteViews views = mw.buildUpdate(getBaseContext());
		ComponentName monitorWidget = new ComponentName(getBaseContext(), MonitorWidget.class);
        appWidgetManager.updateAppWidget(monitorWidget, views);		
	}
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SHOW_PREFERENCES) {
            if (resultCode == RESULT_OK || resultCode == RESULT_CANCELED) {
            	Button refresh_button = (Button) findViewById(R.id.refresh_button);
                if (!pref.getBoolean("gumb_osvezi", true)) {
                	refresh_button.setVisibility(8);
                } else {
                	refresh_button.setVisibility(0);
                }
                refreshWidgets();
            }
        } else if (requestCode == SHOW_WIRELESS_PREFERENCES) {
            if (resultCode == RESULT_OK || resultCode == RESULT_CANCELED) {
            	dismissDialog(DIALOG_NO_CONNECTION);
            }
        }else if (requestCode == SHOW_WIFI_PREFERENCES) {
            if (resultCode == RESULT_OK || resultCode == RESULT_CANCELED) {
            	dismissDialog(DIALOG_NO_WIFI);
            }
        }else if (requestCode == SHOW_MOBILE_PREFERENCES) {
            if (resultCode == RESULT_OK || resultCode == RESULT_CANCELED) {
            	dismissDialog(DIALOG_NO_MOBILE);
            }
        }
    }
	
	private class ItemAdapter extends ArrayAdapter<QuotaItem> {

        private ArrayList<QuotaItem> items;

        public ItemAdapter(Context context, int textViewResourceId, ArrayList<QuotaItem> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.row, null);
                }
                QuotaItem o = items.get(position);
                if (o != null) {
                        TextView tt = (TextView) v.findViewById(R.id.toptext);
                        TextView bt = (TextView) v.findViewById(R.id.bottomtext);
                        if (tt != null) {
                              tt.setText(o.getDisplayName());     
                          }
                        if(bt != null){
                        	if(o.isPrepaid()) {
                        		bt.setText("Porabili ste "+ o.getUsed() +" " + o.getUnit() + " in ostalo vam je še " + o.getAvailable() + " " + o.getUnit());
                        	} else {
                        		bt.setText(o.getUsed() +" "+ o.getUnit());
                        	}
                        }
                }
                return v;
        }
	}
}